package com.gjh.xiaokabang2code.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gjh.xiaokabang2code.async.PreSendMail;
import com.gjh.xiaokabang2code.common.*;
import com.gjh.xiaokabang2code.mapper.BankcardMapper;
import com.gjh.xiaokabang2code.mapper.SearchFinderMapper;
import com.gjh.xiaokabang2code.mapper.UserMapper;
import com.gjh.xiaokabang2code.model.*;
import com.gjh.xiaokabang2code.model.request.SearchLoserRt;
import com.gjh.xiaokabang2code.model.response.LoginRs;
import com.gjh.xiaokabang2code.model.response.LoserRs;
import com.gjh.xiaokabang2code.service.SearchFinderService;
import com.gjh.xiaokabang2code.service.SearchLoserService;
import com.gjh.xiaokabang2code.mapper.SearchLoserMapper;
import com.gjh.xiaokabang2code.service.SuccessMatchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author tsin0
 * @description 针对表【search_loser】的数据库操作Service实现
 * @createDate 2024-03-08 08:58:34
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SearchLoserServiceImpl extends ServiceImpl<SearchLoserMapper, SearchLoser>
        implements SearchLoserService {

    @Resource
    private SearchFinderMapper searchFinderMapper;


    @Resource
    private SuccessMatchService successMatchService;

    @Resource
    private UserMapper userMapper;


    @Autowired
    private CustomMailSender customMailSender;

    @Autowired
    private PreSendMail preSendMail;

    public static final String SALT = "XiaoKabang2Bygjh2003";

    @Override
    public LoserRs searchLoser(SearchLoserRt searchLoserRt, LoginRs loginUser) throws Exception {
        String uBankcard = searchLoserRt.getUBankcard();
        if (uBankcard == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空(S2001)");
        }
        QueryWrapper<SearchFinder> searchFinderQueryWrapper = new QueryWrapper<>();
        searchFinderQueryWrapper.eq("u_bankcard", new DesUtil(SALT).encrypt(uBankcard, "CBC"));
        searchFinderQueryWrapper.eq("status", 0);
        List<SearchFinder> searchFinders = searchFinderMapper.selectList(searchFinderQueryWrapper);
        if (searchFinders.isEmpty()) {
            QueryWrapper<SuccessMatch> successMatchQueryWrapper = new QueryWrapper<>();
            successMatchQueryWrapper.eq("u_bankcard", new DesUtil(SALT).encrypt(uBankcard, "CBC"));
            successMatchQueryWrapper.eq("success_status", 0);
            List<SuccessMatch> listS = successMatchService.list(successMatchQueryWrapper);
            if (listS.size() == 1) {
                SuccessMatch successMatch = listS.get(0);
                String loserUid = successMatch.getLoserUid();
                QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
                userQueryWrapper.eq("u_id", loserUid);
                List<User> users = userMapper.selectList(userQueryWrapper);
                if (users.isEmpty()) {
                    throw new BusinessException(ErrorCode.REPEATING_DATA, "数据库没有该条数据(S2001)");
                }
                if (users.size() > 1) {
                    throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2002)");
                }
                User user = users.get(0);
                LoserRs loserRs = new LoserRs();
                if (user.getNamePrivacy() == 0) {
                    loserRs.setUId(user.getUId());
                    loserRs.setUName(user.getUName());
                    loserRs.setUClass(user.getUClass());
                    loserRs.setUDepartment(user.getUDepartment());
                }
                if (user.getNamePrivacy() == 1) {
                    loserRs.setUId(user.getUId());
                    loserRs.setUPhone(new DesUtil(SALT).decrypt(loserRs.getUPhone(), "CBC"));
                }
                return loserRs;
            }
            QueryWrapper<SearchLoser> searchLoserQueryWrapper = new QueryWrapper<>();
            searchLoserQueryWrapper.eq("u_bankcard", new DesUtil(SALT).encrypt(uBankcard, "CBC"));
            searchLoserQueryWrapper.eq("status", 0);
            long count = this.count(searchLoserQueryWrapper);
            if (count >= 1) {
                return new LoserRs();
            }
            SearchLoser searchLoser = new SearchLoser();
            searchLoser.setUBankcard(new DesUtil(SALT).encrypt(uBankcard, "CBC"));
            searchLoser.setFinderUid(loginUser.getUId());
            searchLoser.setCreateTime(new Date());
            boolean save = this.save(searchLoser);
            if (!save) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增查询丢失用户列表失败(S2002)");
            }
            preSendMail.preSendMailToLoser(uBankcard);
            return new LoserRs();
        }
        if (searchFinders.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2003)");
        }
        SearchFinder searchFinder = searchFinders.get(0);
        searchFinder.setStatus(1);
        int update = searchFinderMapper.update(searchFinder, searchFinderQueryWrapper);
        if (update != 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "更新失败(S2002)");
        }
        String loserUid = searchFinder.getLoserUid();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("u_id", loserUid);
        List<User> users = userMapper.selectList(userQueryWrapper);

        if (users.isEmpty()) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据库没有该条数据(S2001)");
        }
        if (users.size() > 1) {
            throw new BusinessException(ErrorCode.REPEATING_DATA, "数据数目大于1?(S2002)");
        }
        User user = users.get(0);
        LoserRs loserRs = new LoserRs();
        if (user.getNamePrivacy() == 0) {
            loserRs.setUId(user.getUId());
            loserRs.setUName(user.getUName());
            loserRs.setUClass(user.getUClass());
            loserRs.setUDepartment(user.getUDepartment());
        }
        if (user.getNamePrivacy() == 1) {
            loserRs.setUId(user.getUId());
            loserRs.setUPhone(new DesUtil(SALT).decrypt(loserRs.getUPhone(), "CBC"));
        }
        SuccessMatch successMatch = new SuccessMatch();
        successMatch.setLoserUid(loserUid);
        successMatch.setFinderUid(loginUser.getUId());
        successMatch.setUBankcard(new DesUtil(SALT).encrypt(uBankcard, "CBC"));
        successMatch.setCreateTime(new Date());
        boolean save = successMatchService.save(successMatch);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增成功列表失败(S2002)");
        }
        String fourBankcard = HideCharactersUtil.convertToFourDigits(uBankcard);
        String formattedDate = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm");
        String stuNumMail = "vm" + user.getUId() + "@jzxy.edu.cn";
        customMailSender.MailSendToLoser(stuNumMail, formattedDate, fourBankcard);
        return loserRs;
    }
}




